use std::path::PathBuf;
use regex::{Captures, Regex};

static FILE_NAME: &str = "cli-alias-list.toml";

pub fn path_buf_to_string(path_buf: PathBuf) -> String {
  let target_str = path_buf.as_os_str()
    .to_str()
    .expect(format!("path cannot be an string: [{:#?}]", path_buf).as_str());
  String::from(target_str)
}

pub fn get_current_dir() -> PathBuf {
  std::env::current_dir().expect("cannot found current directory")
}

pub fn get_script_dir() -> PathBuf {
  let exe_file = std::env::current_exe().expect("cannot found execute file");
  let parent_path = exe_file.parent().expect(format!("cannout found execute file directory: [{:#?}]", exe_file).as_str());
  parent_path.to_path_buf()
}

pub fn get_config_toml_path_name_list() -> Vec<String> {
  let mut toml_path_list = Vec::<String>::new();
  let mut current_dir = get_current_dir();
  let mut is_current_exist = false;
  current_dir.push(FILE_NAME);
  if current_dir.exists() {
    toml_path_list.push(path_buf_to_string(current_dir.clone()));
    is_current_exist = true;
  }
  let mut script_dir = get_script_dir();
  script_dir.push(FILE_NAME);
  if script_dir.exists() {
    if (is_current_exist && script_dir.ne(&current_dir)) || !is_current_exist {
      toml_path_list.push(path_buf_to_string(script_dir));
    }
  }
  toml_path_list
}

pub fn use_slash_join(path_name: &str) -> String {
  let exp = Regex::new(r"\\+").expect("无法生成正则表达式: /\\+/");
  let result = exp.replacen(path_name, 0, |_: &Captures| {
      return String::from("/");
  });
  return result.to_string();
}
